package com.bmd.backgroundmanger.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bmd.backgroundmanger.commons.QuestionReadListener;
import com.bmd.backgroundmanger.commons.Result;
import com.bmd.backgroundmanger.entity.Question;
import com.bmd.backgroundmanger.service.IQuestionService;
import com.bmd.backgroundmanger.service.impl.QuestionServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 题目管理Controller
 */
@RestController
@RequestMapping("/question")
@Tag(name = "题目管理")
public class QuestionController {

    @Resource
    private IQuestionService questionService;
    
    @Resource
    private QuestionReadListener questionReadListener;

    @PostMapping("/selectPageData")
    @Operation(summary = "分页查询题目列表")
    public Result<Map<String, Object>> selectPageData(
            int page,
            int size,
            @RequestParam(value = "categoryId", required = false) Integer categoryId,
            @RequestParam(value = "questionType", required = false) String questionType,
            @RequestParam(value = "difficultyLevel", required = false) String difficultyLevel,
            @RequestParam(value = "title", required = false) String title) {
        
        // 使用增强版的分页查询
        QuestionServiceImpl questionServiceImpl = (QuestionServiceImpl) questionService;
        Map<String, Object> data = questionServiceImpl.getPageData(page, size, categoryId, questionType, difficultyLevel, title);
        return Result.success(data);
    }

    @PostMapping("/updateAndSave")
    @Operation(summary = "新增/编辑题目")
    public Result<String> updateAndSave(@RequestBody Question question) {
        QuestionServiceImpl questionServiceImpl = (QuestionServiceImpl) questionService;
        boolean success = questionServiceImpl.saveQuestionWithOptions(question);
        
        if (success) {
            if (question.getQuestionId() == null) {
                return Result.success("新增成功!");
            } else {
                return Result.success("修改成功!");
            }
        } else {
            return Result.error(500, "操作失败!");
        }
    }

    @GetMapping("/detail/{id}")
    @Operation(summary = "获取题目详情")
    public Result<Question> getQuestionDetail(@PathVariable Integer id) {
        QuestionServiceImpl questionServiceImpl = (QuestionServiceImpl) questionService;
        Question question = questionServiceImpl.getQuestionWithOptions(id);
        return question != null ? Result.success(question) : Result.error(404, "题目不存在!");
    }

    @DeleteMapping("/delDataById/{id}")
    @Operation(summary = "根据ID删除题目")
    public Result<String> delDataById(@PathVariable Integer id) {
        questionService.removeById(id);
        return Result.success("删除成功");
    }

    @PostMapping("/delDataByIds")
    @Operation(summary = "批量删除题目")
    public Result<String> delDataByIds(@RequestBody List<Integer> ids) {
        questionService.removeBatchByIds(ids);
        return Result.success("批量删除成功!");
    }

    @GetMapping("/searchQuestions")
    @Operation(summary = "搜索题目")
    public Result<List<Question>> searchQuestions(@RequestParam String keyword) {
        List<Question> questions = questionService.searchQuestions(keyword);
        return Result.success(questions);
    }

    @GetMapping("/getRandomQuestion")
    @Operation(summary = "获取随机题目")
    public Result<Question> getRandomQuestion() {
        Question question = questionService.getRandomQuestion();
        return Result.success(question);
    }

    @GetMapping("/getQuestionsByCategory/{categoryId}")
    @Operation(summary = "根据分类获取题目")
    public Result<List<Question>> getQuestionsByCategory(@PathVariable Integer categoryId) {
        List<Question> questions = questionService.getQuestionsByCategoryId(categoryId);
        return Result.success(questions);
    }

    @GetMapping("/getQuestionsByDifficulty/{difficultyLevel}")
    @Operation(summary = "根据难度获取题目")
    public Result<List<Question>> getQuestionsByDifficulty(@PathVariable String difficultyLevel) {
        List<Question> questions = questionService.getQuestionsByDifficultyLevel(difficultyLevel);
        return Result.success(questions);
    }

    @Operation(summary = "导出题目")
    @GetMapping("/exportOut")
    public void exportOut(HttpServletResponse response) {
        try {
            // 1.查询被导出的数据
            List<Question> list = questionService.list();
            System.out.println("查询到题目数量: " + list.size());
            
            // 处理长文本内容，避免Excel导出问题
            for (Question question : list) {
                if (question.getContent() != null && question.getContent().length() > 500) {
                    question.setContent(question.getContent().substring(0, 500) + "...");
                }
            }
            
            // 2.设置响应类型和响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            String fileName = URLEncoder.encode("题目信息", "UTF-8");
            // 告诉浏览器是数据下载
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            
            // 3.将查询出的数据导出
            System.out.println("开始生成Excel文件...");
            EasyExcel.write(response.getOutputStream(), Question.class).sheet("题目信息").doWrite(list);
            System.out.println("Excel文件生成完成");
            
        } catch (Exception e) {
            System.err.println("导出异常: " + e.getMessage());
            e.printStackTrace();
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("导出失败: " + e.getMessage());
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    @Operation(summary = "批量导入题目")
    @PostMapping("/importData")
    public Result<String> importData(MultipartFile file) throws IOException {
        try {
            // 清空之前的数据
            questionReadListener.clear();
            
            // 通过监听器读取xlsx表中第一个sheet数据并封装到Question对象中
            EasyExcel.read(file.getInputStream(), Question.class, questionReadListener).sheet().doRead();
            List<Question> questions = questionReadListener.getQuestions();
            
            // 遍历questions集合将数据存储到数据库中
            for (Question question : questions) {
                question.setQuestionId(null); // 清空ID，让数据库自动生成
                questionService.save(question);
            }
            
            return Result.success("导入成功，共导入" + questions.size() + "条数据!");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(400, "导入失败：" + e.getMessage());
        }
    }
} 